import Vue from 'vue'
import Vuex from 'vuex'
import {
	synchroUserinfo
} from "@/api/login.js"
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		hasRegister: uni.getStorageSync("hasRegister") || false,
		userinfo: {
			// id: null, //  用户id
			// mobile: null,  //  用户手机号
			// openid: null,    //  openid
			nickname: null, //  名
			headimgurl: null, //  头像
			// sex: null,  // 性别 
			// invitation_code: null,  //  邀请码
			type: 1,
			user_level_id: 0,
			status: 1,
			set_pay_password: 0,
			pay_password: null,
			user_account: 0,
			user_red: 0,
			user_virtual_coin: 0,
			user_fans: 0
		},
		openid: uni.getStorageSync("wx_openid") || null,
		unionid: null,
		token: uni.getStorageSync("token") || null,
		addressinfo: null,
		wxuserinfo: uni.getStorageSync("wxuserinfo") || null,
		addressdetail: null, //点编辑数据回显
		buytype: null,
		share_invitation_code: "",
		payback: null,
	},
	mutations: {
		setwxuserinfo(state, wxuserinfo) {
			state.wxuserinfo = wxuserinfo
			uni.setStorageSync("wxuserinfo", wxuserinfo)
		},
		setHasRegister(state, hasRegister) {
			state.hasRegister = hasRegister
			uni.setStorageSync("hasRegister", hasRegister)
		},
		setUserInfo(state, userinfo) {
			state.userinfo = userinfo
		},
		setOpenid(state, openid) {
			state.openid = openid
			uni.setStorageSync("wx_openid", openid)
		},
		setUnionid(state, unionid) {
			state.unionid = unionid
		},
		setToken(state, token) {
			state.token = token
			uni.setStorageSync("token", token)
		},
		setAddressinfo(state, addressinfo) {
			state.addressinfo = addressinfo
		},
		setAddressDetail(state, addressdetail) {
			state.addressdetail = addressdetail
		},
		setBuyType(state, buytype) {
			console.log(buytype);
			state.buytype = buytype
		},
		setShareInvitationCode(state, invitation_code) {
			state.share_invitation_code = invitation_code
		},
		setPayback(state, payback) {
			state.payback = payback
		},
	},
	getters: {},
	actions: {
		updateUserInfo: ({
			commit,
			state
		}) => {
			synchroUserinfo().then(res => {
				console.log(res)
				commit("setUserInfo", res.data)
			})
		}
		// // lazy loading openid
		// getUserOpenId: async function({
		// 	commit,
		// 	state
		// }) {
		// 	return await new Promise((resolve, reject) => {
		// 		if (state.openid) {
		// 			resolve(state.openid)
		// 		} else {
		// 			uni.login({
		// 				success: (data) => {
		// 					commit('login')
		// 					setTimeout(function() { //模拟异步请求服务器获取 openid
		// 						const openid = '123456789'
		// 						console.log('uni.request mock openid[' +
		// 							openid + ']');
		// 						commit('setOpenid', openid)
		// 						resolve(openid)
		// 					}, 1000)
		// 				},
		// 				fail: (err) => {
		// 					console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
		// 					reject(err)
		// 				}
		// 			})
		// 		}
		// 	})
		// }
	}
})

export default store
